<template>
  <a-modal v-model:visible="LAYER.visible" :title="LAYER.title" :width="LAYER.width" :ok-text="LAYER.okText"
           :align-center="LAYER.alignCenter" :top="LAYER.top"
           :closable="false" :unmount-on-close="LAYER.unmountOnClose"
           :mask-closable="LAYER.maskClosable" :esc-to-close="LAYER.escToClose" :ok-loading="LAYER.okLoading"
  >


    <a-row :gutter="12">

      <a-col :span="4">
        <a-select v-model="provinceRegion" placeholder="搜索范围" size="large" allow-search>
          <a-option v-for=" (item,index) in provinceList" :key="index" :label="item" :value="item"/>
        </a-select>
      </a-col>
      <a-col :span="18">

        <a-auto-complete v-model="serchKey" :data="searchResult"
                         placeholder="选择城市后搜索详细地址"
                         clearable
                         @search="querySearchAsync"
                         @select="onselect"
        />
      </a-col>
    </a-row>


    <div id="container"></div>


    <template #footer>
      <a-row class="dialog-footer" justify="space-between">
        <a-col class="map-result" :span="18">
          <span v-if="result.address" style="width: 100%;text-align: right">
            坐标: {{ result.lat }},{{ result.lng }} 位置: {{ result.address }}</span>
        </a-col>
        <a-col class="text-right" :span="6">
          <a-space>


            <a-button @click="onClose(false)">关闭选择器</a-button>
            <a-button :disabled="!result.adCode" type="primary" @click="onsubmit">确定选择</a-button>
          </a-space>
        </a-col>
      </a-row>
    </template>


  </a-modal>
</template>

<script setup lang="ts" name="smart-map-selector">

import {onMounted, reactive, ref} from 'vue'
import {LocalModal} from "@/libs/core";

const TMap = (window as any).TMap;
const emit = defineEmits(["close"])
const props = defineProps({
  modelValue: {
    type: Object,
    required: true,

  },

})


const service = new LocalModal(emit).setMD("位置选择器", '保存设置', 1000)
const {LAYER} = service

let map;
let marker;


const visible = ref(true)


const onClose = (render) => {
  visible.value = false
  emit('close', {render})
}

const result = reactive({
  lat: null,
  lng: null,
  province: null,
  city: null,
  district: null,
  township:null,
  address: null,
  adCode: null
})

const onsubmit = () => {
  emit('close', {render: true, data: {...result}})
  visible.value = false
}

//= ==================

// 标记样式


const serchKey = ref(null)
const searchResult = ref([])

// 换算坐标地址
const geocoderByLocation = async (lat, lng) => {
  const geocoder = new TMap.service.Geocoder()
  const res = await geocoder.getAddress({location: new TMap.LatLng(lat, lng)})

  console.log("地址位置换算结果:",res)
  const {adcode, province, city, district} = res.result.ad_info
  const town =res.result?.address_reference?.town

  result.adCode = adcode
  result.province = province
  result.city = city
  result.district = district
  result.lat = lat
  result.lng = lng
  if (town !==undefined) result.township=town.title
  result.address = res.result.formatted_addresses.standard_address+ res.result.formatted_addresses.recommend


}

const changeCenter = (lat, lng) => {
  const newCenter = new TMap.LatLng(lat, lng);
  map.panTo(newCenter);
}

const addMarker = async (lat, lng) => {
  marker.add({
    id: "customMaker",
    styleId: 'customStyle',
    position: new TMap.LatLng(lat, lng)
  });

}


const removeMarker = () => marker.remove("customMaker")

const getCenterByIp = async () => {
  const runner = new TMap.service.IPLocation()
  const res = await runner.locate()
  const {lat, lng} = res.result.location
  return {lat, lng};
}
// 点击获取经纬度
const clickHandler = (e) => {

  const {lat, lng} = e.latLng
  changeCenter(lat, lng)
  removeMarker()
  addMarker(lat, lng)
  geocoderByLocation(lat, lng)

};
const initMap = async () => {

  map = new TMap.Map(document.getElementById("container"), {
    // 设置地图缩放级别
    zoom: 17,
    // 设置俯仰角
    pitch: 43.5,
    // 设置地图旋转角度
    rotation: 45
  });
// 绑定点击地图获取地理位置的事件
  map.on('click', clickHandler);
}

const initMaker = () => {
  marker = new TMap.MultiMarker({map, geometries: []});
}


const provinceList = ref([])
const loadCityList = async () => {
  // eslint-disable-next-line no-undef
  const district = new TMap.service.District();
  const {result} = await district.list()
  const res = ['宜宾市']
  const x = result[0].map(x => x.fullname)
  provinceList.value = [...res, ...x]
}
const provinceRegion = ref("宜宾市")
// 搜索关联
const getList = async (keyword) => {

  const suggest = new TMap.service.Suggestion({

    pageSize: 10,
    region: provinceRegion.value,
    regionFix: true,
  });

  const {data} = await suggest.getSuggestions({keyword, location: map.getCenter()})

  return data;
}
const querySearchAsync = async (e) => {
  const res = await getList(e)
  searchResult.value = res.map(item => {
    const {address, location: {lat, lng}} = item
    return {value: address, lat, lng}
  })

}
// 点击回掉
const onselect = (e) => {

  const {lat, lng} = searchResult.value.find(x => x.value === e)

  changeCenter(lat, lng)
  removeMarker()
  addMarker(lat, lng)
  geocoderByLocation(lat, lng)
}


onMounted(() => {
  console.log(props)
  setTimeout(async () => {
    await initMap();
    await initMaker();

    if (props.modelValue.lat && props.modelValue.lng) {
      console.log("检测到采纳数了")
      const {lat, lng} = props.modelValue
      await changeCenter(lat, lng)
      await addMarker(lat, lng)
    } else {
      const {lat, lng} = await getCenterByIp();
      changeCenter(lat, lng)
    }


  }, 500)
  loadCityList();
})
</script>

<style lang="less" scoped>
* {
  touch-action: pinch-zoom;

}

#container {

  width: 100%;
  margin-top: 12px;
}
</style>